var app = getApp();
var util = require('../../utils/util.js');
var wxcache = require('../../utils/wxcache.js');
var api = require('../../config/api.js');
var user = require('../../services/user.js');
var isToTopTab = false //和页面参数同步，减少this调用，只有状态改变的时候
var timer
var tabBtnHeight = 0
Page({
  data: {
    
    joinleftinit:40,
    joinUserList:[],
    showJoinNum:false, //
    isPlay:false,
    customerPrice: '',
    customerPrice_qi:'',//多少元起单独定义
    videoBgUrl: '',
    videoUrl:'',
    description: '',
    detailImageUrlHttp: [],
    startAt: '',
    endAt: '',
    likeNum: '',
    name: '',
    price: '',
    
    wantGoNum: '',
    score: 0,
    allscore: 5,
    commentids: [], //commentid状态
    contractId:'',

    journeyDetail: [],
    customerPriceDesc_all: '',
    customerPriceDesc_desc: '',
    // insuranceInfo: '',
    commentInfo: [],
    detailDesc: '',

    is_favourite: 0,
    is_good: 0,
    is_good_comment: 0,
    is_wantgo: 0,
    hasComment: true,
    activity_is_start: false,
    activity_is_done: false,
    currentTab: 0,
    stock: '',
    total: '',
    originStock: '',
    groupNumber: '',
    signupEndTime: '',

    isToTopTab: false,
    loadingHidden: false,
    
    checkLastDate: '',
    resTimeId:'',

    seatInfoList_arr:null,
    seatInfoList: [], //车辆信息
    subCampaignId: [], //子日历id
    subcampaignList:[], //日历时间数组

    personorchild:'',
    descriptionImg:'../../static/imgs/test.jpg'
  },
  toPageTopHeight: [0,0,0,0],
  
  la: '',
  lo: '',
  campaignList: '',
  campaignid: '',
  locationId: '',
  locationProvince: '',
  locationCity: '',
  primaryImageUrl: [],
  loginFlag:false,
  addressArray:[],
  status:"ONLINE",


  // onPageScroll: function (e) {
  //   //  console.log(e)
  //   // console.log(tabBtnHeight)
  //   if (e.scrollTop > tabBtnHeight) {
  //     this.setData({
  //       isToTopTab: true
  //     })
  //   }else {
  //     this.setData({
  //       isToTopTab: false
  //     })
  //   }

  //   clearTimeout(timer)
  //   timer = setTimeout(() => {
  //     var max=0;
  //     this.toPageTopHeight.forEach((v, k) => {
  //       // console.log(v, k, e)
  //       if (e.scrollTop + 40 >= v){
  //         // console.log(v, k, e)
  //         max=k
  //       } 
  //     })
    
  //     this.setData({
  //       currentTab:max
  //     })
  //   }, 200)
    
  // },
  hiddenvideo:function(event){

    this.setData({
      isPlay:false
    })
  },
  showvideo:function(event){
    this.setData({
      isPlay: true
    })
  },
  toJoinNum:function(e){
 
    wx.navigateTo({
      url: '/pages/goodsjoin/goodsjoin?id='+this.campaignid,
    })

  },
   
  //图片点击事件
  imgPreview: function (event) {
    var src = event.currentTarget.dataset.src;//获取data-src
    var imgList = event.currentTarget.dataset.list;//获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },

  toWeatherPage: function () {

    wx.navigateTo({
      url: '/pages/weather/weather?la=' + this.la + '&lo=' + this.lo + '&poiName=' + this.data.poiName + "&city=" + this.locationCity,
    })
  },
  //获取已报名人数
  getJoinNum:function(){

    var that = this;
    util.request(api.JoinNum + this.campaignid).then(function (res) {

        console.log("res:",res)
      if (res.responseBody.data.length > 0){
        that.setData({
          showJoinNum:true,
          joinUserList: res.responseBody.data 
        })
      }
    })
  },
  
  onLoad: function (options) {
    this.campaignid = parseInt(options.id)
  },

  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    
    this.getActivityInfo();
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  //显示报名人数蒙层
  showJoin:function(e){



  },
  //立即报名
  activityRegistration: function (e) {

    console.log(e);

    user.checkLogin().then(res => {

      user.getUserinfoByButton(e).then(res => {
        
        var that = this;
        var seatStock = "";
        var stylePrice = "";
        var subCampaignId = "";
        //检查是否选择了日历
        if (that.data.personorchild == '') {
          //检查是否选择了成人/儿童
          wx.showModal({
            title: '提示',
            content: '请选择成人/儿童',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
              } else {
                console.log('用户点击取消');
              }
            }
          })
          return;
        }else if (that.data.resTimeId == '') {
          wx.showModal({
            title: '提示',
            content: '请选择出行日期',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
              } else {
                console.log('用户点击取消');
              }
            }
          })
          return;
        }else{
          for (var i = 0; i < that.data.subCamInfoList.length; i++){
            if (that.data.resTimeId == that.data.subCamInfoList[i].id){
              that.setData({
                seatInfoList: that.data.subCamInfoList[i].seatInfoList
              })
              seatStock = that.data.subCamInfoList[i].seatInfoList[0].seatStock;//获取座位信息
              stylePrice = JSON.stringify(that.data.subCamInfoList[i].campaignFeeList);//获取分类价格信息
              subCampaignId = that.data.subCamInfoList[i].id;//获取日历子活动id
              if(that.data.personorchild == '成人'){
                that.setData({
                  customerPrice: that.data.subCamInfoList[i].price//成人价格
                })
              } else if (that.data.personorchild == '儿童'){
                that.setData({
                  customerPrice: that.data.subCamInfoList[i].juvenilePrice//儿童价格
                })
              }
              continue;
            }
          }
          wx.navigateTo({
            url: '/pages/indent/indent?id=' + that.campaignid + '&seatStock=' + seatStock + '&subCampaignId=' + subCampaignId + '&stylePrice=' + stylePrice + '&description=' + that.data.description + '&contractId=' + that.data.contractId +'&customerPrice=' + that.data.customerPrice + '&personOrChild=' + that.data.personorchild + '&name=' + that.data.name + '&checkLastDate=' + that.data.checkLastDate + '&seatInfoList=' + JSON.stringify(that.data.seatInfoList) + '&startAt=' + that.data.startAt + '&endAt=' + that.data.endAt + '&primaryImageUrl=' + that.primaryImageUrl[0] + '&addressArray=' + JSON.stringify(that.addressArray) ,
          });
        }
      })
    }).catch(() => {
      //未登录跳转至登录页面
      wx.showModal({
        title: '提示',
        content: '请登录后进行报名',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            user.getUserinfoByButton(e)
            wx.navigateTo({
              url: '/pages/auth/registerAndLogin/registerAndLogin',
            })
          } else {
            console.log('用户点击取消');
          }
        }
      })

    });
  },

 
 
 
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
      console.log(this.toPageTopHeight[cur] + 400, this.toPageTopHeight)
      // wx.pageScrollTo({
      //   scrollTop: this.toPageTopHeight[cur] - 40,
      //   duration: 0
      // })
    }
     
  },

  clickToDate:function(e){

      var _this = this;
      wx.navigateTo({
        url: '/pages/goods/calendar/calendar?name=' + _this.data.name + '&data_arr=' + JSON.stringify(_this.data.subcampaignList)
      })
  },
 
  clickToMap: function (e) {
    var that = this;
    wx.openLocation({
      latitude: that.la, // 纬度，范围为-90~90，负数表示南纬  
      longitude: that.lo, // 经度，范围为-180~180，负数表示西经 
      scale: 18,
      name: that.data.poiName,
      address: that.data.poiAddress
    })
    //更新想去人数
    this.bind_wantgo();
  },


  formatDate: function(now) {

    var year = now.getFullYear();  //取得4位数的年份

    var month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月

    var date = now.getDate();      //返回日期月份中的天数（1到31）

    var hour = now.getHours();     //返回日期中的小时数（0到23）

    var minute = now.getMinutes(); //返回日期中的分钟数（0到59）

    var second = now.getSeconds(); //返回日期中的秒数（0到59）

    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;

  },

  //  获取 某一活动的详细情况
  getActivityInfo: function () {

    let that = this;

    user.checkLogin().then(function(succ){
      that.loginFlag = true

    },function(err){
      that.loginFlag = false
    })

    var data = {campaignId:that.campaignid};

    util.request(api.ActivityUrl, data,"GET").then(function (res) {
      console.log(res);
      var campaignList = res.campaignList[0];
      console.log(campaignList)
      
      var c = campaignList.subCamInfoList;
        //var c_arr = ["2019-11-29","2019-11-30","2019-12-01","2019-12-10"];//测试数据
        var c_arr = [];
        for(var i=0; i<c.length; i++){
          var d = new Date(c[i].startAt);//创建一个指定的日期对象
          var ford = that.formatDate(d);
          ford = ford.trim().split(" ")[0];
          var id = c[i].id;
          c_arr.push({ id: id, time: ford});
        }
        that.setData({
          
          customerPrice: campaignList.customerPrice,
          customerPrice_qi: campaignList.customerPrice,
          description: campaignList.description,
          detailImageUrlHttp: campaignList.detailImageUrl,                                                                                                                                                   
          startAt: campaignList.startAt,
          endAt: campaignList.endAt,
          likeNum: campaignList.likeNum,

          contractId: campaignList.contractId,
          
          name: campaignList.name,
          price: campaignList.price,
          wantGoNum: campaignList.wantGoNum,
          
          journeyDetail: campaignList.journeyDetail,
          poiName: campaignList.poiName,
          poiAddress: campaignList.poiAddress,
          score: campaignList.score,
          detailDesc: JSON.parse(campaignList.activityDetailDesc),
          customerPriceDesc_all: campaignList.customerPriceDesc,
          stock: campaignList.stock, 
          total: campaignList.total,
          originStock: campaignList.originStock,
          groupNumber: campaignList.groupNumber,
          signupEndTime: campaignList.signupEndTime,
          videoBgUrl: campaignList.videoBgUrl ? campaignList.videoBgUrl :'',
          videoUrl: campaignList.videoUrl ? campaignList.videoUrl[0] :'' , //视频只会有一个，取第一个
          
          seatInfoList_arr:campaignList.seatInfoList,
          subCampaignId:campaignList.subCampaignId,
          subcampaignList: c_arr,
          subCamInfoList: campaignList.subCamInfoList
        })
          that.status = campaignList.status
          that.campaignList = campaignList,
          that.lo =  campaignList.longitude,
          that.la = campaignList.latitude,
          that.locationId = campaignList.locationId,
          that.locationProvince = campaignList.locationId.split(" ")[0],
          that.locationCity = campaignList.locationId.split(" ")[1],
          that.primaryImageUrl = campaignList.primaryImageUrl,
            that.addressArray = campaignList.boardingLocation ? campaignList.boardingLocation :[] 


        //获取活动保险信息
        // util.request(api.InsuranceInfo, { "campaignId": that.campaignid }).then(function (res) {
        //   console.log(res);
        //   that.setData({
        //     insuranceInfo: res.responseBody.insuranceDetailList
        //   });
        // });

        //判断用户是否登录,并判断用户是否对活动的点赞想去收藏有过操作

          if (that.loginFlag) {

            if (that.campaignList.favorite == 0) {
              that.setData({
                is_favourite: 0
              });

            } else if (that.campaignList.favorite == 1) {
              that.setData({
                is_favourite: 1
              });
            }

            if (that.campaignList.likes == 0) {
              that.setData({
                is_good: 0
              });
            } else if (that.campaignList.likes == 1) {
              that.setData({
                is_good: 1
              });
            }

            if (that.campaignList.wantGo == 0) {
              that.setData({
                is_wantgo: 0
              });
            } else if (that.campaignList.wantGo == 1) {
              that.setData({
                is_wantgo: 1
              });
            }
          }
      
      that.checkExpire()
      //获取评价信息
      that.getComment();
      that.getJoinNum();
      

    }).then(res => {

      // setTimeout(this.getCardTop, 1000) 
      that.setData({
        loadingHidden: true
      })
    
    })
  },

  // 获取每个卡片的top值并记录下来
  getCardTop() {
    var list = [1,2,3,4]
    list.forEach((v, k) => {
      wx.createSelectorQuery().select('#s' + v).boundingClientRect((res) => {
        console.log(res)
        this.toPageTopHeight[k] = res.top
      }).exec()
    })
    setTimeout(() => {
      wx.createSelectorQuery().select('#tabBtn').boundingClientRect((res) => {
        // console.log(res.top, 'tabBtn')
        tabBtnHeight = res.top
      }).exec()
    }, 100)
  },
  formatNumber:function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  /**
   * 判断活动是否开始或结束
  */
  checkExpire: function () {
    var _this = this;
    var sctl = this.data.subCamInfoList;
    var siet = this.data.signupEndTime;
    var sctlStr = "";
    for(var i=0; i<sctl.length; i++){
      if((i-1)>=0){
        var sctl_i = sctl[i].startAt;
        var sctl_ii = sctl[i-1].startAt;
        if (((new Date(sctl_i.replace(/-/g, "\/"))) > (new Date(sctl_ii.replace(/-/g, "\/")))) == true){
          //sctl_i晚于sctl_ii则返回true
          sctlStr = sctl_ii;
        }else{
          sctlStr = sctl_i;
        }
      }
    }
    sctlStr = sctlStr + " 00:00:00";
    var sctlStrDate = new Date(sctlStr);
    // var d1 = new Date('2016/03/28 10:17:22');
    // var d2 = new Date('2016/03/28 11:17:22');

    var year = new Date().getFullYear();
    var month = new Date().getMonth() + 1;
    var day = new Date().getDate();
    var hour = new Date().getHours();
    var minute = new Date().getMinutes();
    var second = new Date().getSeconds();
    var crentTime = new Date([year, month, day].map(_this.formatNumber).join('-') + ' ' + [hour, minute, second].map(_this.formatNumber).join(':'));

    var cTime = parseInt(sctlStrDate - crentTime) / 6000;

    var sietArr = siet.split(":");
    var sietAll = sietArr[0] * 60 + sietArr[1];

    //var startAt = new Date(this.data.startAt.replace(/-/g, "/"))
    var signupEndTime = new Date(this.data.signupEndTime.replace(/-/g,"/"))
    var stock = this.data.stock
    var now = new Date()

    // 如果超过报名时间，没库存，超过开始时间任意一个，显示报名已结束
    //var dd1 = now - signupEndTime;
    //var dd2 = now - sctlStrDate;
    var dd3 = parseInt(sietAll) - cTime;
    if (stock == 0 || this.status != "ONLINE" ||  dd3 > 0 ){
      this.setData({
        activity_is_start: true
      })
    }else{
      this.setData({
        activity_is_start: false
      })
    }
  },
  //获取评价接口,评价信息赋值给变量commendids
  getComment: function () {
    let that = this;

    util.request(api.CommentUrl + that.campaignid).then(function (res) {

      if (res.responseBody.length > 0) {
        // console.log(res.responseBody);
        that.setData({
          commentInfo: res.responseBody,
        })
      } else {
        // console.log("评价信息为空");
        that.setData({
          hasComment: false
        })
      }
    })
  },
  bind_favourite: function () {
    user.checkLogin().then(res => {
      // console.log("已登录")
      if (this.data.is_favourite == 0) {
        this.setData({
          is_favourite: 1
        });
      } else if (this.data.is_favourite == 1) {
        this.setData({
          is_favourite: 0
        });
      }
      this.updateFavorite();

    }, function (err) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.switchTab({
              url: '/pages/ucenter/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    })
  },

  bind_good: function () {
    user.checkLogin().then(res => {
      console.log("已登录")
      if (this.data.is_good == 0) {
        this.setData({
          is_good: 1,
          likeNum: this.data.likeNum + 1

        });
      } else if (this.data.is_good == 1) {
        this.setData({
          is_good: 0,
          likeNum: this.data.likeNum - 1
        });
      }
      this.updateLikes();
    }, function (err) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.switchTab({
              url: '/pages/ucenter/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    })
  },

  bind_wantgo: function () {

    var that = this;

    user.checkLogin().then(res => {

      if (that.data.is_wantgo == 0) {
        that.setData({
          is_wantgo: 1
        });

        that.updateWantGo();
      }
    })
  },

  bind_good_comment: function (e) {
    var that = this;
    console.log(e)
    var cid = e.currentTarget.dataset.commentid

    user.checkLogin().then(res => {

      if (that.data.is_good_comment == 0) {
        that.setData({
          is_good_comment: 1,
        });
        that.data.commentids.push(e.currentTarget.dataset.commentid)
      } else if (that.data.is_good_comment == 1) {
        that.setData({
          is_good_comment: 0,
        });
        that.data.commentids.pop(e.currentTarget.dataset.commentid)
      }

      that.updateCommentLikes(e);


    }, function (error) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否登录',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.switchTab({
              url: '/pages/ucenter/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    })

  },


  /**
   * 添加取消收藏
   */
  updateFavorite: function () {
    var uid = wxcache.get("userInfo").id
    var data = {}
    data.flag = this.data.is_favourite; // 1 是  0 否
    data.campaignId = this.campaignid;
    data.userId = uid;
    util.request(api.UpdateFavorite, data, 'POST').then(function (res) {
      console.log("收藏返回值")
      console.log(res)
    })
  },

  /**
   * 添加取消点赞
   * 
  */
  updateLikes: function () {

    var uid = wxcache.get("userInfo").id
    var data = {}
    data.flag = this.data.is_good; // 1 是  0 否
    data.campaignId = this.campaignid;
    data.userId = uid;
    util.request(api.UpdateLikes, data, 'POST').then(function (res) {
      console.log("点赞返回值")
      console.log(res)
    })
  },

  /**
 * 添加取消评论点赞
 * 
*/
  updateCommentLikes: function (e) {

    var uid = wxcache.get("userInfo").id
    var data = {}
    data.flag = this.data.is_good_comment; // 1 是  0 否
    data.commentId = e.currentTarget.dataset.commentid;
    data.userId = uid;
    util.request(api.UpdateCommentLike, data, 'POST').then(function (res) {
      console.log("评论点赞返回值")
      console.log(res)
    })
  },

  /**
   * 添加取消想去
  */
  updateWantGo: function () {
    var uid = wxcache.get("userInfo").id
    var data = {}
    data.flag = this.data.is_wantgo; // 1 是  0 否
    data.campaignId = this.campaignid;
    data.userId = uid;
    util.request(api.UpdateWantGo, data, 'POST').then(function (res) {

      console.log("想去返回值")
      console.log(res)
    })
  },

  /**
   * 进入商城
   */
  gotoshangcheng:function(){
    var _this = this;
    wx.navigateTo({
      url: '../goods/commoditylist/commoditylist?goodId=' + _this.campaignid,
    })
  },

  /**
   * 获取子活动信息
   */
  getChildGoodsInfo:function(){
    var _this = this;
    var url = api.subCampaignQuery + this.campaignid;
    util.request(url,'GET').then(function (res) {
      var sc_id = _this.data.subCampaignId;
      console.log("子活动返回值：")
      console.log(res)
      if(res.code == 200){
        for(var i=0; i<res.responseBody.length; i++){
          if(res.responseBody[i].id == sc_id){
            res.responseBody[i];
          } 
        }
      }
    })
  },

  selectPersonOrChild:function(){
    var _this = this;
    wx.showActionSheet({
      itemList: ['成人', '儿童'],
      success(res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0){
          _this.setData({
            personorchild: '成人'
          })
        }
        if (res.tapIndex == 1) {
          _this.setData({
            personorchild: '儿童'
          })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  }


})